<?php
declare (strict_types = 1);

namespace app\controller;

use app\BaseController;
use app\model\Address;
use think\Request;

class AddressController extends BaseController
{
	protected $middleware = [
		'Login' => ['except' => ['']],
	];
	/**
	 * 新增地址
	 * @return void
	 */
	function addAddress(Request $request)
	{
		$name = $request->post('name');
		$mobile = $request->post('mobile');
		$province = $request->post('province');
		$city = $request->post('city');
		$region = $request->post('region');
		$address = $request->post('address');
		$default = $request->post('default/d',0);

		$data = [
			'name' => $name,
			'mobile' => $mobile,
			'province' => $province,
			'city' => $city,
			'region' => $region,
			'address' => $address,
			'user_id' => $this->user_id,
		];
		if ($default == 0) {
			$row = Address::where(['user_id' => $this->user_id, 'default' => 1])->find();
			if (!$row) {
				$data['default'] = 1;
			}
		} else {
			Address::where(['user_id' => $this->user_id, 'default' => 1])->update(['default' => 0]);
			$data['default'] = 1;
		}
		Address::create($data);
		$this->writeJson();
	}
	
	/**
	 * 设置默认地址
	 * @return void
	 */
	function setDefaultAddress(Request $request)
	{
		$id = $request->post('id/d');
		Address::where(['user_id' => $this->user_id])->update(['default' => 0]);
		Address::where(['id' => $id])->update(['default' => 1]);
		$this->writeJson();
	}
	
	/**
	 * 获取默认地址
	 * @return void
	 */
	function getDefaultAddress()
	{
		$row = Address::where(['user_id' => $this->user_id, 'default' => 1])->find();
		$this->writeJson($row);
	}
	
	
	/**
	 * 编辑地址
	 * @param Request $request
	 * @param int $id
	 * @return void
	 */
	function editAddress(Request $request, int $id)
	{
		$AddressModel = new Address();
		$row = $AddressModel->find($id);
		if (!$request->isPost()) {
			$this->writeJson($row);
		}
		$params = $request->post();
		if (isset($params['default'])&&$params['default'] == 1) {
			$AddressModel->where(['user_id' => $this->user_id])->save(['default' => 0]);
		}
		$row->save($params);
		$this->writeJson();
	}
	
	/**
	 * 删除地址
	 * @param Request $request
	 * @return void
	 */
	function delAddress(Request $request)
	{
		$id = $request->post('id/d');
		$row = Address::where(['user_id'=>$this->user_id])->findOrFail($id);
		$row->delete();
		$this->writeJson();
	}
	
	/**
	 * 地址列表
	 * @return void
	 */
	function listAddress()
	{
		$rows = Address::where(['user_id' => $this->user_id])->order(['id' => 'desc'])->paginate()->items();
		$this->writeJson($rows);
	}
	
}
